package thread.synchroCode;

import java.util.Deque;
import java.util.LinkedList;

// 生产者消费者问题
public class _03ProductConsume {
  public static void main(String[] args) {
    Factory factory = new Factory(10);

    new Thread(()-> {
      for (int i = 0; i < 100; i++) {
        System.out.println(factory.consume());
      }
    }).start();

    new Thread(()-> {
      for (int i = 0; i < 100; i++) {
        factory.product(String.valueOf(i));
        System.out.println("入队"+ i);
      }
    }).start();
  }

  // 再来一个工厂，里面提供消费者和生产者的方法
  public static class Factory{
    BlockedQueue blockedQueue;

    public String consume(){
      return blockedQueue.poll();
    }

    public void product(String string){
      blockedQueue.offer(string);
    }

    public Factory(int size) {
      blockedQueue = new BlockedQueue(10);
    }
  }

  // 先来一个阻塞队列
  public static class BlockedQueue {
    private int size;
    Deque<String> queue = new LinkedList<>();

    public BlockedQueue(int size) {
      this.size = size;
    }

    public void offer(String str){
      synchronized (queue){
        while (queue.size() >= size){
          try {
            queue.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        queue.addFirst(str);
        queue.notifyAll();
      }
    }

    public String poll(){
      synchronized (queue){
        while (queue.size() == 0){
          try {
            queue.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        String poll = queue.poll();
        queue.notifyAll();
        return poll;
      }
    }
  }
}
